import { invoke } from '@tauri-apps/api';
import { basename } from '@tauri-apps/api/path';
import { Button, notification } from 'antd';
import type { ReactNode } from 'react';
import React, { useContext } from 'react';
import { CONFIG_KEYS, RESPONSE_STATUS } from '../../constants/config';
import { Handle } from '../../lib/handle';
import type { Modules } from '../../lib/modules/interface';
import { FillContext } from '../app/Fill';

export interface IExportProps {
  disabled?: boolean
  text?: string
  module?: Modules
  upload?: boolean
  children?: ReactNode
}

export const Export: React.FC<IExportProps> = ({ text, module = 'all', upload = true, children, disabled = false }) => {
  const {
    setLoading,
    setLoadingText,
    config,
    loading,
  } = useContext(FillContext);
  const handleExport = async () => {
    setLoading(true);
    setLoadingText('加载中');
    try {
      const handle = new Handle();
      setLoadingText('准备数据');
      const manager = await handle.export(module);

      const length = Object.values(manager.results).map(item => item.data.length).reduce((prev, item) => prev + item);
      console.log(length);
      if (!length) {
        notification.error({
          message: '未查询到可导出数据',
        });
        setLoading(false);
        return;
      }

      setLoadingText('加密导出');
      await manager.generate(true);
      setLoadingText('更新记录');
      await manager.update();

      if (upload) {
        const serve = config[CONFIG_KEYS.SERVER][0];
        const slug_id = config[CONFIG_KEYS.F_XCZDX_REF_ID_];
        const slug = config[CONFIG_KEYS.F_XCZDX_NAME_];

        setLoadingText('上传提报');
        // const uint8: Uint8Array = await readBinaryFile(manager.data);
        // console.log(uint8);
        // const blob = new Blob([uint8.buffer]);
        // const form = new FormData();
        // const file_name = await basename(manager.data);
        // form.append('file', blob, file_name);

        try {
          // await axios.post(`http://${serve.F_IP_}/dataPacket/transfer/uploadByTool?id=${id}&slug=${slug}`, form);
          // const ids = new Uint32Array(1);
          // window.crypto.getRandomValues(ids);
          // const id = ids[0];
          console.log(`http://${serve.F_IP_}/api/api-ida/dataPacket/transfer/uploadByTool?id=${slug_id}&slug=${slug}`);
          const response = await invoke<{ value: RESPONSE_STATUS }>('reqwest_multipart_form', {
            // id,
            remote: `http://${serve.F_IP_}/api/api-ida/dataPacket/transfer/uploadByTool?id=${slug_id}&slug=${slug}`,
            targetFile: manager.data,
            fileName: await basename(manager.data),
            // headers: {
            //   'Content-Type': 'multipart/form-data',
            // },
          });

          console.log(response);

          response.value === RESPONSE_STATUS.SUCCESS
            ? notification.success({
              message: '提报成功',
            })
            : notification.error({
              message: '提报失败',
            });
        }
        catch (error) {
          console.log(error);
          notification.error({
            message: '导出成功,提报失败',
          });
        }

        // const result = await invoke('upload_file', {
        //   remote: `http://${serve.F_IP_}/dataPacket/transfer/uploadByTool?id=${id}&slug=${slug}`,
        //   targetFile: manager.data,
        // });

        // !result && notification.error({
        //   message: '提报失败',
        // });
      }
      else {
        notification.success({
          message: '导出成功',
        });
      }
    }
    catch (error) {
      console.log(error);
    }
    setLoading(false);
  };

  return (
    <>
      {
        children
          ? <div onClick={handleExport}>{children}</div>
          : (<Button type="primary" loading={loading} onClick={handleExport} disabled={disabled}>{text}</Button>)
      }
    </>
  );
};
